package com.xd.common.util;

import com.xd.common.constant.SysConstant;
import com.xd.common.exception.XkdException;
import com.xd.core.company.entity.Company;
import com.xd.core.system.entity.LoginUser;
import com.xd.core.system.entity.SysUser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
public class SecurityUtil {
    /**
     * 当前用户
     *
     * @return
     */
    public static LoginUser getLoginUser() {
        UsernamePasswordAuthenticationToken authentication =
                (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();

        return (LoginUser) authentication.getPrincipal();
    }

    public static LoginUser getLoginUser0() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (null == authentication) return null;
        Object user = authentication.getPrincipal();
        if (user instanceof LoginUser)
            return (LoginUser) user;
        return null;
    }

    /**
     * 当前用户id
     *
     * @return
     */
    public static Integer getLoginUserId() {
        return getLoginUser().getUser().getId();
    }

    /**
     * 当前用户所属公司id
     *
     * @return
     */
    public static Integer getLoginCompanyId() {
        SysUser user = getLoginUser().getUser();
        if (user.getCompanyType().equals(SysConstant.USER_COMPANY_TYPE_ONE))
            return SysConstant.SUPER_COMPANY_ID;
        return getLoginCompany().getId();
    }

    /**
     * 当前用户所属公司信息
     *
     * @return
     */
    public static Company getLoginCompany() {
        return getLoginUser().getCompany();
    }

    /*
     * 获取当前用户部门ID
     * */
    public static Integer getGroupId() {
        return getLoginUser().getGroupId();
    }

    /**
     * 获取当前用户是否为主账号
     */
    public static Boolean isPrimaryAccount() {
        return getLoginUser().getUser().getUserType().equals(SysConstant.USER_TYPE_P);
    }

    /**
     * 判断资方电子账户是否申请通过
     */
    public static void isCompanyAccountApply() {
        Company loginCompany = getLoginCompany();
        if (loginCompany != null){//代表不是平台
            if (loginCompany.getCompanyType().equals("1")){//资方
                if (StringUtils.isBlank(loginCompany.getPrestoreNo()))
                    throw new XkdException("资方未申请电子账户，禁止调用");
                if (!loginCompany.getPrestoreApplyStatus().equals(SysConstant.ACCOUNT_APPLY_STATUS_THREE))
                    throw new XkdException("资方电子账户尚未申请成功，禁止调用");
            }else {//代理
                throw new XkdException("代理方无权查看");
            }
        }
    }



}
